package com.zwl9517hotmail.libplaymedia;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.LinkedHashMap;

import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerManager;

/**
 * Created by ZouWeiLin
 * on 2017/11/24  16:02
 * version:
 * desc:    播放媒体类，外接只需关注把该fragment注入到指定的容器里，并提供视频地址
 */
public class PlayMediaFragment extends Fragment {

    private static final String KEY_LINK_MAP = "LINK_MAP";
    private static final String KEY_IS_REPEAT = "KEY_IS_REPEAT";
    private static final String KEY_REPEAT_COUNT = "KEY_REPEAT_COUNT";

    private LinkedHashMap linkedHashMap;    // 数据源，可以是本地地址，也可以是url
    private boolean isRepeat;               // 是否重复播放
    private int repeatCount;                // 重复次数，目前暂时没做功能

    public static PlayMediaFragment newInstance(LinkedHashMap linkedHashMap, boolean needRepeat, int repeatCount) {
        PlayMediaFragment fragment = new PlayMediaFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(KEY_LINK_MAP, linkedHashMap);
        bundle.putBoolean(KEY_IS_REPEAT, needRepeat);
        bundle.putInt(KEY_REPEAT_COUNT, repeatCount);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_play_media, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        JZVideoPlayerAutoPlay.startFullscreen(getActivity(), JZVideoPlayerAutoPlay.class, linkedHashMap, 0);
        JZVideoPlayer player = JZVideoPlayerManager.getCurrentJzvd();
        if (player != null) {
            if (player instanceof JZVideoPlayerAutoPlay) {
                ((JZVideoPlayerAutoPlay) player).setRepeat(isRepeat);

            }
        }
    }

    private void initData() {
        if (getArguments() != null) {
            Bundle bundle = getArguments();
            linkedHashMap = (LinkedHashMap) bundle.getSerializable(KEY_LINK_MAP);
            isRepeat = bundle.getBoolean(KEY_IS_REPEAT);
            repeatCount = bundle.getInt(KEY_REPEAT_COUNT);
        }
    }
}
